package com.feishi.core.socket.netty.handler;

import com.feishi.core.analytic.assembler.BaseAssembler;
import com.feishi.core.socket.common.lifecycle.SocketSession;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

/**
 * Created by caixq on 2/22 022.
 */
public class NettyHandler<T extends BaseAssembler> extends ChannelHandlerAdapter {
    private SocketSession session;

    protected SocketNettyHandler handler=new SocketNettyHandler();

    public NettyHandler(SocketSession session) {
        this.session=session;
        this.handler.setSession(session);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        handler.setCtx(ctx);
        handler.onConnect(ctx.channel().remoteAddress());

        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        handler.setCtx(ctx);
        handler.onDisconnect(ctx.channel().remoteAddress());
        super.channelInactive(ctx);
    }

    public SocketNettyHandler getHandler() {
        return handler;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        handler.onMsg((BaseAssembler) msg);
    }

    public void setHandler(SocketNettyHandler handler) {
        this.handler = handler;
        if(this.handler!=null){
            this.handler.setSession(session);
        }
    }
}
